import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Resource } from './entities/resource.entity';
import * as fs from 'fs';
import * as path from 'path';
// import { Jimp } from "jimp";
@Injectable()
export class ResourceService {
    constructor(
        @InjectRepository(Resource)
        private resourceRepository: Repository<Resource>,
    ) { }

    async findByMd5(md5: string): Promise<Resource> {
        // return this.resourceRepository.findOne({ where: { md5 } });
        const resource = await this.resourceRepository.findOne({ where: { md5 } });
        if (resource) {
            // 更新创建时间为当前时间
            resource.created_at = new Date();
            await this.resourceRepository.save(resource);
        }
        return resource;
    }

    async saveResource(resource: Resource): Promise<Resource> {
        return this.resourceRepository.save(resource);
    }

    async deleteByMd5(md5: string): Promise<void> {
        const resource = await this.resourceRepository.findOne({ where: { md5 } });
        if (resource) {
            if (resource.path) {
                try {
                    // 检查并删除原文件
                    const originalPath = `${process.env.FILE_PATH}/${resource.name}`;
                    if (fs.existsSync(originalPath)) {
                        fs.unlinkSync(originalPath);
                    }

                    // 删除缩略图（如果存在）
                    const ext = path.extname(resource.name);
                    const baseName = path.basename(resource.name, ext);
                    const thumbnailPath = `${process.env.FILE_PATH}/${baseName}.min${ext}`;

                    if (fs.existsSync(thumbnailPath)) {
                        fs.unlinkSync(thumbnailPath);
                    }

                    await this.resourceRepository.delete(resource.id);
                } catch (error) {
                    console.error('删除文件失败:', error);
                }
            }
            await this.resourceRepository.delete(resource.id);
        }
    }

    async findWithPagination(page: number, limit: number): Promise<[Resource[], number]> {
        const [resources, total] = await this.resourceRepository.findAndCount({
            skip: (page - 1) * limit,
            take: limit,
            order: {
                created_at: 'DESC'  // 按创建时间倒序排序
            }
        });
        return [resources, total];
    }

    async createThumbnail(file, thumbnailPath) {
        // 读取图片
        // const image = await Jimp.read(file.path);

        // // 计算缩放后的尺寸，保持宽高比且不放大原始尺寸小于目标尺寸的图片
        // let width = image.bitmap.width;
        // let height = image.bitmap.height;
        // const targetSize = 300;

        // if (width > height) {
        //     if (width < targetSize) {
        //         // 如果宽度小于目标尺寸，则不放大
        //         width = width;
        //         height = height;
        //     } else {
        //         // 缩放宽度到目标尺寸，高度按比例调整
        //         height = Math.floor(height * (targetSize / width));
        //         width = targetSize;
        //     }
        // } else {
        //     if (height < targetSize) {
        //         // 如果高度小于目标尺寸，则不放大
        //         width = width;
        //         height = height;
        //     } else {
        //         // 缩放高度到目标尺寸，宽度按比例调整
        //         width = Math.floor(width * (targetSize / height));
        //         height = targetSize;
        //     }
        // }

        // // 调整大小
        // image.resize({ w: width, h: height });

        // // 保存缩略图
        // image.write(thumbnailPath);
    }
}